<template>
  <div class="student-guidance">
    <div class="page-header">
      <h1 class="page-title">指导学生成果</h1>
      <div class="header-actions">
        <el-button type="success" @click="exportData">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
        <el-button type="primary" @click="openForm()">新增指导记录</el-button>
      </div>
    </div>

    <el-card>
      <div class="filter-bar">
        <el-select v-model="filters.studentType" placeholder="学生类型" clearable style="width: 140px;" @change="fetchList">
          <el-option label="本科生" value="本科生" />
          <el-option label="硕士生" value="硕士生" />
          <el-option label="博士生" value="博士生" />
        </el-select>
        <el-select v-model="filters.achievementType" placeholder="成果类型" clearable style="width: 140px; margin-left: 12px;" @change="fetchList">
          <el-option label="竞赛" value="获奖" />
          <el-option label="项目" value="项目" />
          <el-option label="论文" value="论文" />
        </el-select>
        <el-input v-model="filters.level" placeholder="级别/分区" clearable style="width: 160px; margin-left: 12px;" @keyup.enter.native="fetchList" />
        <el-input v-model="filters.year" placeholder="年份" clearable style="width: 100px; margin-left: 12px;" @keyup.enter.native="fetchList" />
        <el-button type="primary" style="margin-left: 12px;" @click="fetchList">查询</el-button>
      </div>

      <el-table :data="rows" stripe v-loading="loading">
        <el-table-column prop="studentName" label="学生姓名" width="120" />
        <el-table-column prop="studentType" label="学生类型" width="100" />
        <el-table-column prop="guidanceCategory" label="指导内容" width="120" />
        <el-table-column label="指导起止" width="220">
          <template #default="{ row }">{{ formatDate(row.startDate) }} ~ {{ formatDate(row.endDate) }}</template>
        </el-table-column>
        <el-table-column prop="guidanceTopic" label="主题/课题" min-width="160" />
        <el-table-column label="成果" min-width="240">
          <template #default="{ row }">
            <span v-if="row.achievements && row.achievements.length">{{ row.achievements[0].achievementType }}｜{{ row.achievements[0].title }}</span>
            <span v-else>-</span>
            <el-button v-if="row.achievements && row.achievements.length>1" type="primary" text size="small" style="margin-left:8px;" @click="openAllAchievements(row)">查看全部</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }"><el-tag :type="statusTag(row.status)">{{ statusText(row.status) }}</el-tag></template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <el-button type="text" @click="view(row)">查看</el-button>
            <el-button type="text" @click="edit(row)">编辑</el-button>
            <el-button type="text" style="color:#f56c6c;" @click="remove(row)" v-if="row.status==='PENDING'">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog v-model="showAllAchievements" title="全部成果" width="700px">
      <el-table :data="allAchievements" border>
        <el-table-column prop="achievementType" label="类型" width="120" />
        <el-table-column prop="title" label="标题/名称" min-width="280" />
        <el-table-column prop="level" label="级别/分区" width="160" />
        <el-table-column prop="achievementDate" label="日期" width="120">
          <template #default="{ row }">{{ formatDate(row.achievementDate) }}</template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button @click="showAllAchievements=false">关闭</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="showForm" :title="editing ? '编辑指导记录' : '新增指导记录'" width="900px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="16">
          <el-col :span="12"><el-form-item label="学生姓名" prop="studentName"><el-input v-model="form.studentName" /></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="学生类型" prop="studentType">
            <el-select v-model="form.studentType" style="width: 100%">
              <el-option label="本科生" value="本科生" />
              <el-option label="硕士生" value="硕士生" />
              <el-option label="博士生" value="博士生" />
            </el-select>
          </el-form-item></el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12"><el-form-item label="指导内容" prop="guidanceCategory">
            <el-select v-model="form.guidanceCategory" style="width: 100%">
              <el-option label="毕业论文" value="毕业论文" />
              <el-option label="大创项目" value="大创项目" />
              <el-option label="学科竞赛" value="学科竞赛" />
              <el-option label="科研训练" value="科研训练" />
            </el-select>
          </el-form-item></el-col>
          <el-col :span="12"><el-form-item label="主题/课题"><el-input v-model="form.guidanceTopic" /></el-form-item></el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12"><el-form-item label="开始日期" prop="startDate"><el-date-picker v-model="form.startDate" type="date" value-format="YYYY-MM-DD" style="width: 100%" @change="onStartDateChangeForm" /></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="结束日期" prop="endDate"><el-date-picker v-model="form.endDate" type="date" value-format="YYYY-MM-DD" :disabled-date="disableEndBeforeStart" style="width: 100%" /></el-form-item></el-col>
        </el-row>

        <el-divider content-position="left">成果信息</el-divider>
        <el-button type="primary" size="small" @click="addAchievement">添加成果</el-button>
        <el-table :data="form.achievements" style="margin-top: 8px;">
          <el-table-column label="类型" width="140">
            <template #default="{ row }">
              <el-select v-model="row.achievementType" style="width: 100%">
                <el-option label="竞赛" value="获奖" />
                <el-option label="项目" value="项目" />
                <el-option label="论文" value="论文" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="标题/名称" min-width="220">
            <template #default="{ row }"><el-input v-model="row.title" /></template>
          </el-table-column>
          <el-table-column label="级别/分区" width="160">
            <template #default="{ row }"><el-input v-model="row.level" /></template>
          </el-table-column>
          <el-table-column label="日期" width="160">
            <template #default="{ row }"><el-date-picker v-model="row.achievementDate" type="date" value-format="YYYY-MM-DD" style="width: 100%" /></template>
          </el-table-column>
          <el-table-column label="证明材料" min-width="260">
            <template #default="{ row }">
              <el-upload :auto-upload="false" :show-file-list="false" accept=".pdf,.jpg,.jpeg,.png,.doc,.docx,.ppt,.pptx"
                         :on-change="(file)=>onSelectAttachment(row, file)"
              >
                <el-button size="small">选择附件</el-button>
              </el-upload>
              <span v-if="row._attachmentName" style="margin-left:8px; color:#909399;">{{ row._attachmentName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template #default="{ $index }">
              <el-button type="text" style="color:#f56c6c;" @click="removeAchievement($index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <el-button @click="showForm=false">取消</el-button>
        <el-button type="primary" :loading="saving" @click="submit">保存</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="showView" title="指导详情" width="800px">
      <el-descriptions :column="2" border v-if="current">
        <el-descriptions-item label="学生姓名">{{ current.studentName }}</el-descriptions-item>
        <el-descriptions-item label="学生类型">{{ current.studentType }}</el-descriptions-item>
        <el-descriptions-item label="指导内容">{{ current.guidanceCategory }}</el-descriptions-item>
        <el-descriptions-item label="主题/课题">{{ current.guidanceTopic || '-' }}</el-descriptions-item>
        <el-descriptions-item label="起始日期">{{ formatDate(current.startDate) }}</el-descriptions-item>
        <el-descriptions-item label="结束日期">{{ formatDate(current.endDate) }}</el-descriptions-item>
        <el-descriptions-item label="审核状态"><el-tag :type="statusTag(current.status)">{{ statusText(current.status) }}</el-tag></el-descriptions-item>
        <el-descriptions-item label="审核意见">{{ current.reviewOpinion || '-' }}</el-descriptions-item>
      </el-descriptions>
      <el-divider content-position="left">成果</el-divider>
      <el-table :data="current?.achievements || []" border>
        <el-table-column prop="achievementType" label="类型" width="120" />
        <el-table-column prop="title" label="标题/名称" min-width="220" />
        <el-table-column prop="level" label="级别/分区" width="160" />
        <el-table-column prop="achievementDate" label="日期" width="120">
          <template #default="{ row }">{{ formatDate(row.achievementDate) }}</template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button @click="showView=false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Download } from '@element-plus/icons-vue'
import studentGuidanceApi from '@/api/studentGuidance'

const loading = ref(false)
const rows = ref([])
const filters = ref({ studentType: '', achievementType: '', level: '', year: '' })

const showForm = ref(false)
const saving = ref(false)
const editing = ref(false)
const formRef = ref()
const form = ref({
  studentName: '', studentType: '', guidanceCategory: '', guidanceTopic: '', startDate: '', endDate: '',
  achievements: []
})

const rules = {
  studentName: [{ required: true, message: '请输入学生姓名', trigger: 'blur' }],
  studentType: [{ required: true, message: '请选择学生类型', trigger: 'change' }],
  guidanceCategory: [{ required: true, message: '请选择指导内容', trigger: 'change' }],
  startDate: [{ required: true, message: '请选择开始日期', trigger: 'change' }],
  endDate: [
    { required: true, message: '请选择结束日期', trigger: 'change' },
    {
      validator: (_, value, cb) => {
        if (!form.value.startDate || !value) return cb()
        if (new Date(value) < new Date(form.value.startDate)) {
          cb(new Error('结束日期不能早于开始日期'))
        } else cb()
      },
      trigger: 'change'
    }
  ],
  // 至少添加一个成果
  achievements: [
    {
      validator: (_, value, cb) => {
        if (!form.value.achievements || form.value.achievements.length === 0) {
          cb(new Error('请至少添加一个成果'))
        } else cb()
      },
      trigger: 'change'
    }
  ]
}

const showView = ref(false)
const current = ref(null)
const showAllAchievements = ref(false)
const allAchievements = ref([])

function formatDate(v){ if(!v) return '-'; return String(v).substring(0,10) }
function statusText(s){ if(!s) return '待审核'; if(s==='APPROVED') return '已通过'; if(s==='REJECTED') return '已驳回'; return '待审核' }
function statusTag(s){ const t=statusText(s); return t==='已通过'?'success':(t==='已驳回'?'danger':'info') }

function addAchievement(){ form.value.achievements.push({ achievementType: '', title: '', level: '', achievementDate: '', extra: '' }) }
function removeAchievement(i){ form.value.achievements.splice(i,1) }

function onStartDateChangeForm(val){
  // 自动将结束日期设为开始日期，提升体验
  if (!form.value.endDate || new Date(form.value.endDate) < new Date(val)) {
    form.value.endDate = val
  }
}
function disableEndBeforeStart(date){
  if (!form.value.startDate) return false
  return date.getTime() < new Date(form.value.startDate).getTime()
}

function onSelectAttachment(row, file){
  row._attachmentFile = file.raw
  row._attachmentName = file.name
}

function openForm(){ editing.value=false; form.value={ studentName:'', studentType:'', guidanceCategory:'', guidanceTopic:'', startDate:'', endDate:'', achievements:[] }; showForm.value=true }
function edit(row){ editing.value=true; form.value={ studentName:row.studentName, studentType:row.studentType, guidanceCategory:row.guidanceCategory, guidanceTopic:row.guidanceTopic, startDate:formatDate(row.startDate), endDate:formatDate(row.endDate), achievements:(row.achievements||[]).map(a=>({ achievementType:a.achievementType, title:a.title, level:a.level, achievementDate:formatDate(a.achievementDate), extra:a.extra })) }; form.value.id=row.id; showForm.value=true }

async function submit(){
  try{
    await formRef.value.validate()
    saving.value = true
    const payload = { ...form.value }
    // 先提交主数据
    let id = form.value.id
    if(editing.value){ await studentGuidanceApi.update(form.value.id, payload); id = form.value.id; ElMessage.success('更新成功') }
    else { id = await studentGuidanceApi.create(payload); ElMessage.success('创建成功') }

    // 上传每条成果的附件（如果有选择）
    try{
      for (const ach of form.value.achievements) {
        if (ach._attachmentFile && ach._tempId) {
          await studentGuidanceApi.uploadAchievementAttachment(ach._tempId, ach._attachmentFile)
        }
      }
    } catch (e) { console.warn('附件上传失败或未选择', e) }

    showForm.value=false; fetchList()
  }catch(e){} finally{ saving.value=false }
}

async function fetchList(){
  try{
    loading.value=true
    const res = await studentGuidanceApi.my({ studentType: filters.value.studentType || undefined, achievementType: filters.value.achievementType || undefined, level: filters.value.level || undefined, year: filters.value.year || undefined })
    rows.value = res?.content || res || []
  }catch(e){ console.error(e); ElMessage.error('获取列表失败') } finally { loading.value=false }
}

async function view(row){ try{ current.value = await studentGuidanceApi.getById(row.id); showView.value=true }catch(e){} }
function openAllAchievements(row){ allAchievements.value = (row.achievements||[]); showAllAchievements.value = true }
async function remove(row){ try{ await ElMessageBox.confirm(`删除"${row.studentName}"的指导记录？`,'确认',{type:'warning'}); await studentGuidanceApi.delete(row.id); ElMessage.success('删除成功'); fetchList() }catch(e){} }

const exportData = async () => {
  const { exportData: exportUtil } = await import('@/utils/exportUtils')
  
  const exportFilters = {
    search: filters.value.level,
    type: filters.value.achievementType
  }
  
  await exportUtil('student-guidance', exportFilters, '学生指导列表.xlsx')
}

onMounted(fetchList)
</script>

<style scoped>
.student-guidance { max-width: 1400px; }
.page-header { display:flex; justify-content:space-between; align-items:center; margin-bottom:24px; }
.page-title { margin:0; color:#333; font-size:24px; font-weight:500; }
.filter-bar { margin-bottom:16px; display:flex; align-items:center; flex-wrap:wrap; gap:12px; }
</style> 